package com.chenl.provider.controller;

import com.alibaba.ttl.threadpool.TtlExecutors;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chenl.proextend.idempotent.Idempotent;
import com.chenl.provider.DEMOS.多线程相关.AsyncMethodClazz;
import com.chenl.provider.DTO.UserInfo;
import com.chenl.provider.DTO.entity.MyStudent;
import com.chenl.provider.feign.ConFeign;
import com.chenl.provider.mapper.StuMapper;
import com.chenl.provider.service.StudentServiceImpl;
import com.chenl.provider.util.FileUtils;
import com.chenl.provider.util.RedisLock;
import com.chenl.provider.util.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.ApplicationContext;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@RestController
@RequestMapping("/test")
@RefreshScope
@Slf4j
public class TesttController extends ServiceImpl<StuMapper, MyStudent> {
    public static void main(String[] args) {

    }

    @Autowired
    ConFeign conFeign;
    @Autowired
    RedisService redisService;
    @Autowired
    StuMapper stuMapper;
    @Value("${test.value:猪皮}") //设置默认值
    private String testName;

    @Value("${test.value2}")
    private String testName2;
//    @Value(value = "${test.testt}")
    private String name;

    @Autowired
    RedisLock redisLock;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    StudentServiceImpl studentService;

    @Autowired
    AsyncMethodClazz asyncMethodClazz;

    @Autowired
    ApplicationContext applicationContext;



//    @Value("${test.test}")
//    private String test;

    ExecutorService executorService = Executors.newSingleThreadExecutor();

//    TransmittableThreadLocal<String> context = new TransmittableThreadLocal<>();

//    ThreadPoolExecutor executor = new ThreadPoolExecutor(1,1,1, TimeUnit.MINUTES,new ArrayBlockingQueue<>(1));
    ExecutorService executor=Executors.newSingleThreadExecutor();

    ThreadLocal<Object> local = new InheritableThreadLocal<>();



    @PostMapping(value = "/test")
    public Object test2(@RequestBody Map<String,Object> map) throws Exception {
                executor = TtlExecutors.getTtlExecutorService(executor);
        if (map.get("key")!=null){
            local.set((String)map.get("key"));
        }
        System.out.println("打印0:"+local.get()+" "+Thread.currentThread().getName());
        executor.execute(()->{
            System.out.println("打印1:"+local.get()+" "+Thread.currentThread().getName());
        });
        local.set(2);
        System.out.println("打印2:"+local.get()+" "+Thread.currentThread().getName());
        executor.execute(()->{
            System.out.println("打印3:"+local.get()+" "+Thread.currentThread().getName());
        });
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("打印4:"+local.get()+" "+Thread.currentThread().getName());
            }
        }).start();
        local.remove();
        return "result";
    }

    @PostMapping("/testt")
//    @Idempotent
    public String test(@RequestBody UserInfo userInfo,HttpServletRequest request) throws Exception {
//        response.sendRedirect("http://10.190.176.240:20004/frontend/#/user/login");
//        response.sendRedirect("https://m.fjtic.cn/frontend/#/user/mobileLogin?uid=02334537");
//        response.sendRedirect("https://m.fjtic.cn/frontend/#/");
//        response.sendRedirect("https://10.190.176.240:20004/frontend/#/user/mobileLogin?uid=02334537");
        log.info("拿到请求头traceId了:"+request.getHeader("traceId"));
//        System.out.println("开始睡觉");
//        Thread.sleep(10000);
//        System.out.println("结束睡觉，抛出异常");
//        throw new RuntimeException("报错了");
        return "ok";
    }

    @Autowired
    TestService testService;



    @GetMapping("/test2")
    public String test2() throws Exception {
        testService.method();
        return "ok";
    }


//    @Autowired
//    MaterialFeign materialFeign;

//    @Autowired
//    CategoryFeign categoryFeign;
//
//    @Autowired
//    CategoryPropertyFeign categoryPropertyFeign;
//
//    @Autowired
//    DeviceRecordFeign deviceRecordFeign;
//
//    @Autowired
//    ItemFeign itemFeign;
//
//    @Autowired
//    ModelTypeFeign modelTypeFeign;
//
//    @Autowired
//    ModelTypeRelationFeign modelTypeRelationFeign;
//
//    @Autowired
//    ProductionLineDeviceFeign productionLineDeviceFeign;
//
//    @Autowired
//    PropertyFeign property;
//
//    @Autowired
//    PropertyGroupFeign propertyGroupFeign;
//
//    @Autowired
//    RecipeStandardFeign recipeStandardFeign;
//
//    @Autowired
//    RecipeStandardDetailFeign recipeStandardDetailFeign;
//
//    @Autowired
//    SkuFeign skuFeign;
//
//    @Autowired
//    TechnicsStandardFeign technicsStandardFeign;
//
//    @Autowired
//    TechnicsStandardDetailFeign technicsStandardDetailFeign;
//
//    @Autowired
//    TobaccoMaterialFeign tobaccoMaterialFeign;
//
//    @Autowired
//    TobaccoMaterialDetailFeign tobaccoMaterialDetailFeign;
//
//    @Value("${chenling.test.test:654}")
//    String test;
//
//
//
//
//    @GetMapping("/test4")
//    public String test4() throws Exception {
//        System.out.println(test);
//        String property = applicationContext.getEnvironment().getProperty("bizworks-api-gateway.type");
//        System.out.println(property);
////        Result<List<CategoryPropertyResDto>> listResult = categoryPropertyFeign.getCategoryPropertyListNoPage(new MapUtils());
////        Result<Pager<DeviceRecordResDto>> deviceRecordList = deviceRecordFeign.getDeviceRecordList(new MapUtils());
////        System.out.println(JSONObject.toJSONString(deviceRecordList));
////        Result<List<CategoryResDto>> categoryList = categoryFeign.getCategoryListNoPage(new MapUtils());
////        System.out.println(JSONObject.toJSONString(categoryList));
////        Result<CategoryPropertyResDto> categoryPropertyResDtoResult = categoryPropertyFeign.updateCategoryPropertyById(1L, new CategoryPropertyReqDto());
////        System.out.println(JSONObject.toJSONString(categoryPropertyResDtoResult));
//        Result<List<PropertyGroupResDto>> propertyGroupListNoPage = propertyGroupFeign.getPropertyGroupListNoPage(new MapUtils());
//        System.out.println(JSONObject.toJSONString(propertyGroupListNoPage));
////        Result<CategoryPropertyResDto> categoryPropertyOne = categoryPropertyFeign.getCategoryPropertyOne(new MapUtils());
////        System.out.println(JSONObject.toJSONString(categoryPropertyOne));
////        Result<List<CategoryPropertyResDto>> categoryPropertyListNoPage = categoryPropertyFeign.getCategoryPropertyListNoPage(new MapUtils());
////        System.out.println(JSONObject.toJSONString(categoryPropertyListNoPage));
//        return "ok";
//
//    }

    @GetMapping("/test3")
    public String test3() throws Exception {
//        String property = applicationContext.getEnvironment().getProperty("spring.application.name");
//        String property2 = applicationContext.getEnvironment().getProperty("bizworks-api-gateway.type");
//        Result<Pager<ModelTypeResDto>> allModelType = modelFeign.getAllModelType(new MapUtils());
//        log.info("666:"+allModelType);
//        ModelTypeReqDto modelTypeReqDto = new ModelTypeReqDto();
//        modelTypeReqDto.setModel("ZBM15");
//        Result<ModelTypeResDto> modelTypeResDtoResult = modelFeign.updateModelType(1707209487244632065l, modelTypeReqDto);
//        log.info("777:"+modelTypeResDtoResult);
//        MapUtils mapUtils = new MapUtils();
//        mapUtils.put("ids","58,99");
//        Result<Boolean> booleanResult = modelFeign.deleteByIds(mapUtils);
//        log.info("888:"+booleanResult);
        return "ok";

    }








    @Transactional  //自己使用事务管理器手动管理事务不加这个注解
    @PostMapping(value = "/mybatis")
    public String testt2() throws Exception {


        return testName;
    }

    @PostMapping(value = "/upload")
    public String upload(@RequestParam("file") MultipartFile file,String dirPath) throws Exception {
        FileUtils.uploadByMultipartFile(file,dirPath,file.getOriginalFilename());
        return "ok";
    }
    @Autowired
    FileUtils fileUtils;

    @PostMapping(value = "/uploadToResources")
    public String uploadToResources(@RequestParam("file") MultipartFile file,String path) throws Exception {
        fileUtils.outPutByMultFile(file,path+"/static/"+file.getOriginalFilename());
        return "ok";
    }



    /**
     * 获取项目路径下的文件,若不存在则创建
     *
     * @return 文件
     */
    public static File getUploadPath(String relativePath) {
        try {
            File path = new File(ResourceUtils.getURL("resources:").getPath());
            if (!path.exists()) {
                path = new File("");
            }
            File upload = new File(path.getAbsolutePath(), relativePath);
            if (!upload.exists()) {
                boolean r = upload.mkdirs();
                if (!r) {
                    log.info("创建临时路径失败。。。");
                    return null;
                }
            }
            return upload;
        } catch (FileNotFoundException e) {
            return null;
        }
    }
}
